package de.alexhepp.widgets.messagewidget;

import java.io.InputStream;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.PhoneLookup;
import android.telephony.PhoneNumberUtils;
import android.util.Log;

public class MessageUtils {

	private static final String LOG_TAG = "MessageUtils";

	public static ContactInfo getContact(Context context, long senderId, String phoneNr) {
		ContactInfo info = new ContactInfo();
		// fill the ContactInfo object.
		//Log.v(LOG_TAG, "trying to create contact with:" + senderId + ", nr:" + phoneNr);
		info.setDisplayName(getPersonName(context, senderId, phoneNr));
		info.setContactPhoto(getPersonPhoto(context, senderId));
		return info;
	}

	/**
	 * Looks up a contacts id, given their address (phone number in this case).
	 * Returns null if not found
	 */
	public static long getContactIdFromPhoneNumber(Context context,
			String address) {
		if (address == null) {
			//Log.v(LOG_TAG, "no given number:" + address);
			return -1;
		}
		//Log.v(LOG_TAG, "looking up contact id for number:" + address);
		Cursor contactLookupCursor = context.getContentResolver().query(
				Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
						Uri.encode(address)),
				new String[] { PhoneLookup.DISPLAY_NAME, Contacts._ID},
				null, null, null);
		try {
			while (contactLookupCursor.moveToNext()) {
				String contactName = contactLookupCursor.getString(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
				long contactId = contactLookupCursor.getLong(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup._ID));
				//Log.d(LOG_TAG, "contactMatch name: " + contactName);
				//Log.d(LOG_TAG, "contactMatch id: " + contactId);

				return contactId;
			}
		} finally {
			contactLookupCursor.close();
		}
		Log.v(LOG_TAG, "could not find person for number:" + address);
		return -1;
	}

	/**
	 * Looks up a contacts display name by contact id - if not found, the
	 * address (phone number) will be formatted and returned instead.
	 */
	public static String getPersonName(Context context, long contactId, String address) {
		if (contactId == 0) {
			if (address != null) {
				//Log.v(MessageWidget.LOG_TAG,"Contact not found, trying from phone number");
				contactId = getContactIdFromPhoneNumber(context, address);
			} else {
				return null;
			}
		}
		if (contactId == -1) {
//			Log.v(MessageWidget.LOG_TAG, "Contact not found, formatting number");
			return PhoneNumberUtils.formatNumber(address);
		} else {

	        Cursor cursor = context.getContentResolver().query(
	                Uri.withAppendedPath(Contacts.CONTENT_URI, String.valueOf(contactId)),
	                new String[] { Contacts.DISPLAY_NAME },
	                null, null, null);

			if (cursor != null) {
				try {
					if (cursor.getCount() > 0) {
						cursor.moveToFirst();
						String name = cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME));
//						Log.v(MessageWidget.LOG_TAG, "Contact Display Name: "+ name);
						return name;
					} else {
//						Log.v(MessageWidget.LOG_TAG, "Person with id: " + contactId + " was not found.");
					}
				} finally {
					cursor.close();
				}
			}
		}

		return null;
	}
	
	/**
	 * Looks up a contacts photo by their contact id, returns a byte array that
	 * represents their photo (or null if not found)
	 */
	public static Bitmap getPersonPhoto(Context context, long contactId) {
		Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);

		return loadContactPhoto(context, uri);
	}

	/**
	 * Opens an InputStream for the person's photo and returns the photo as a
	 * Bitmap. If the person's photo isn't present returns the
	 * placeholderImageResource instead.
	 * 
	 * @param context
	 *            the Context
	 * @param id
	 *            the id of the person
	 * @param options
	 *            the decoding options, can be set to null
	 */
	public static Bitmap loadContactPhoto(Context context, Uri contactUri) {

		final InputStream stream;

		stream = Contacts.openContactPhotoInputStream(context.getContentResolver(), contactUri);
		if(stream == null){
			Log.e(LOG_TAG,"could not get a stream for contact photo.");
			return null;
		}
		BitmapFactory.Options options = new BitmapFactory.Options();
		Bitmap bm = BitmapFactory.decodeStream(stream, null, options);
		if (bm == null) {
//			Log.v(LOG_TAG, "Person does not have a photo.");
		}
		return bm;
	}
}
